import json
import math
from common import replaces, requests, thresholds
from common.integrates import SignRequest


class DataProcess:
    sign_request = SignRequest()
    query_buffer = {}
    query_buffer = {}
    connect_number = 0

    def __init__(self, vehicle_name):
        self.request_body = requests[vehicle_name]
        self.judge_threshold = thresholds[vehicle_name]
        self.replace_field = replaces[vehicle_name]

    def process(self):
        query_data = self.query(self.request_body)
        replace_data = self.replace(query_data)
        compare_data = self.compare(replace_data)
        binary_data = self.binary(compare_data)
        return binary_data

    def query(self, request_body):
        try:
            resp = self.sign_request.post(
                "/open-api/supos/oodm/v2/attribute/current", request_body
            )

            query_data = json.loads(resp.text)  # type: ignore
            if query_data["code"] == 200:
                return query_data["data"]
            else:
                return {"The client request was failed!"}
        except Exception as exp:
            print("supos query data failure!" + str(exp))
            return {"supos query data failure!"}

    def replace(self, query_data):
        replace_data = {}
        for index, value in query_data.items():
            if query_data[index]:
                replace_data[self.replace_field[index]] = value["value"]
            else:
                replace_data[self.replace_field[index]] = None
        return replace_data

    def compare(self, replace_data):
        compare_data = {}
        print(
            "connect number is %s ,buffer is %s"
            % (self.connect_number, self.query_buffer)
        )
        self.connect_number += 1
        if self.query_buffer == {}:
            self.query_buffer = replace_data
            compare_data = replace_data
            return compare_data
        else:
            for index, value in replace_data.items():
                print("index , value is %s %s" % (index, value))
                if value == None:
                    value = 0
                if math.fabs(
                    (0 if value == None else float(value))
                    - (
                        0
                        if self.query_buffer[index] == None
                        else float(self.query_buffer[index])
                    )
                ) > float(self.judge_threshold[index]):
                    compare_data[index] = value
                else:
                    compare_data[index] = self.query_buffer[index]
                self.query_buffer = replace_data
            return compare_data

    def binary(self, compare_data):
        binary_data = json.dumps(compare_data, indent=4, ensure_ascii=False)
        return binary_data
